<template>
  <el-dialog :title="title" v-model="dialogVisible" width="600px" destroy-on-close @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="上级菜单">
        <el-tree-select
          v-model="form.parent_id"
          :data="menuOptions"
          placeholder="请选择上级菜单"
          :props="{
            value: 'menu_id',
            label: (data: any) => data.title || data.name || '未命名菜单',
            children: 'children'
          }"
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="路由名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入路由名称" />
      </el-form-item>
      <el-form-item label="路由路径" prop="path">
        <el-input v-model="form.path" placeholder="请输入路由路径" />
      </el-form-item>
      <el-form-item label="组件路径" prop="component">
        <el-input v-model="form.component" placeholder="请输入组件路径" />
      </el-form-item>
      <el-form-item label="重定向地址" prop="redirect">
        <el-input v-model="form.redirect" placeholder="请输入重定向地址" />
      </el-form-item>
      <el-form-item label="菜单标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入菜单标题" />
      </el-form-item>
      <el-form-item label="菜单图标" prop="icon">
        <el-input v-model="form.icon" placeholder="请输入菜单图标">
          <template #append>
            <el-popover
              v-model:visible="iconSelectorVisible"
              popper-class="icon-selector-popper"
              trigger="click"
              :width="300"
            >
              <template #reference>
                <el-button>
                  <vab-icon :icon="form.icon" v-if="form.icon" />
                  <span>{{ form.icon ? '更换图标' : '选择图标' }}</span>
                  <vab-icon icon="arrow-down-s-line" class="arrow-icon" />
                </el-button>
              </template>
              <vab-icon-selector @handle-icon="handleIcon" />
            </el-popover>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="自定义图标">
        <el-switch v-model="form.is_custom_svg" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :label="1">菜单</el-radio>
          <el-radio :label="2">页面/按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限标识" prop="perms">
        <el-input v-model="form.perms" placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="是否隐藏">
        <el-switch v-model="form.hidden" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="是否缓存">
        <el-switch v-model="form.no_keep_alive" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createMenu, updateMenu } from '/@/api/menu'
import type { MenuForm } from '/@/api/menu'

// 修改 Props 类型定义，明确 menuOptions 的类型
interface MenuOption {
  menu_id: number
  title: string
  children?: MenuOption[]
}

const props = defineProps<{
  visible: boolean
  type: 'add' | 'edit'
  menuOptions: MenuOption[]
  currentRow?: any
}>()

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const title = computed(() => props.type === 'add' ? '新增菜单' : '编辑菜单')

const formRef = ref<FormInstance>()

const defaultForm: MenuForm = {
  parent_id: 0,
  name: '',
  path: '',
  component: 'Layout',
  redirect: '',
  title: '',
  icon: '',
  is_custom_svg: 0,
  type: 1,
  perms: '',
  sort: 0,
  hidden: 0,
  no_keep_alive: 0,
  status: 1,
}

const form = reactive<MenuForm>({ ...defaultForm })

const rules = reactive<FormRules>({
  title: [
    { required: true, message: '菜单标题不能为空', trigger: 'blur' },
    { max: 32, message: '菜单标题最多32个字符', trigger: 'blur' }
  ],
  name: [
    { max: 32, message: '路由名称最多32个字符', trigger: 'blur' }
  ],
  path: [
    { max: 255, message: '路由路径最多255个字符', trigger: 'blur' }
  ],
  component: [
    { max: 255, message: '组件路径最多255个字符', trigger: 'blur' }
  ],
  redirect: [
    { max: 255, message: '重定向地址最多255个字符', trigger: 'blur' }
  ],
  icon: [
    { max: 32, message: '图标最多32个字符', trigger: 'blur' }
  ],
  perms: [
    { max: 100, message: '权限标识最多100个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '菜单类型不能为空', trigger: 'change' }
  ],
  sort: [
    { type: 'number', message: '排序必须为数字', trigger: 'change' }
  ],
  parent_id: [
    { type: 'number', message: '父级ID必须为数字', trigger: 'change' }
  ],
  is_custom_svg: [
    { type: 'number', validator: (rule: any, value: any, callback: any) => {
      if (value !== 0 && value !== 1) {
        callback(new Error('自定义图标值只能是0或1'))
      } else {
        callback()
      }
    }, trigger: 'change' },
  ],
  status: [
    { type: 'number', validator: (rule: any, value: any, callback: any) => {
      if (value !== 0 && value !== 1) {
        callback(new Error('状态值只能是0或1'))
      } else {
        callback()
      }
    }, trigger: 'change' },
  ],
  no_keep_alive: [
    { type: 'number', validator: (rule: any, value: any, callback: any) => {
      if (value !== 0 && value !== 1) {
        callback(new Error('是否缓存值只能是0或1'))
      } else {
        callback()
      }
    }, trigger: 'change' },
  ],
  hidden: [
    { type: 'number', validator: (rule: any, value: any, callback: any) => {
      if (value !== 0 && value !== 1) {
        callback(new Error('是否隐藏值只能是0或1'))
      } else {
        callback()
      }
    }, trigger: 'change' },
  ]
})

const iconSelectorVisible = ref(false)

// 初始化表单数据
const initFormData = () => {
  if (props.type === 'edit' && props.currentRow) {
    Object.assign(form, props.currentRow)
  } else {
    Object.assign(form, defaultForm)
    if (props.currentRow) {
      form.parent_id = props.currentRow.menu_id || 0
    }
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (props.type === 'edit' && !form.menu_id) {
          ElMessage.error('菜单ID不能为空')
          return
        }
        
        if (props.type === 'add') {
          await createMenu(form)
          ElMessage.success('新增成功')
        } else {
          await updateMenu(form)
          ElMessage.success('更新成功')
        }
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    initFormData()
  }
})

// 处理图标选择
const handleIcon = (icon: string) => {
  form.icon = icon
  iconSelectorVisible.value = false
}

</script>

<style lang="scss" scoped>

.icon-selector-popper {
  width: 302px !important;

  .vab-query-form {
    margin-top: calc(var(--el-margin) / 2);

    .el-input {
      width: 220px;
    }
  }

  .el-card__body {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 25px;
    cursor: pointer;

    [class*='ri-'] {
      font-size: 28px;
      color: var(--el-color-grey);
      text-align: center;
      pointer-events: none;
      cursor: pointer;
    }
  }

  .el-pagination {
    margin-top: calc(0 - var(--el-margin)) !important;
  }
}
</style> 